import { useMutation } from '@tanstack/react-query';
import { App } from 'antd';
import { useNavigate } from 'react-router-dom';
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { StorageEnum } from '../constants/layout';
import { envConfig } from '@/api/integration'
import { getInfo } from '@/api/integration'
import { getLocation } from "@/utils";


const { VITE_APP_HOMEPAGE: HOMEPAGE } = import.meta.env;

const useUserStore = create()(
  persist(
    (set, get) => ({
      loginHintInfo: { show: false },
      userInfo: {},
      userToken: '',
      constantObjSSO: {},
      actions: {
        setLoginHint: (data) => {
          set({ loginHintInfo: data });
        },
        setUserInfo: (userInfo) => {
          set({ userInfo });
        },
        setUserToken: (userToken) => {
          set({ userToken });
        },
        setSSO: (constantObjSSO) => {
          set({ constantObjSSO });
        },
        clearUserInfoAndToken() {
          set({ userInfo: {}, userToken: '', constantObjSSO: {} });
        },
        getEnvConfig: async () => {
          let data = await envConfig();
          set({ constantObjSSO: data || {} });
          return data
        },

        getUserInfo: async () => {
          if (!get().userToken) return {}
          let data = await getInfo(get().userToken);
          set({ userInfo: data?.user || {} });
          return data
        },
        logout() {
          set({ userInfo: {}, userToken: '' })
          localStorage.removeItem('access_token')
        },
        toSSOLogout: () => {
          getLocation().href = `http://${get().constantObjSSO.SSO_HOST}/esc-sso/logout`
        },
      },
    }),
    {
      name: 'userStore', // name of the item in the storage (must be unique)
      storage: createJSONStorage(() => localStorage), // (optional) by default, 'localStorage' is used
      partialize: (state) => ({
        // [StorageEnum.UserInfo]: state.userInfo,
        [StorageEnum.UserToken]: state.userToken,
        [StorageEnum.ConstantObjSSO]: state.constantObjSSO,
      }),
    },
  ),
);

export const useUserLoginHintInfo = () => useUserStore((state) => state.loginHintInfo);
export const useUserInfo = () => useUserStore((state) => state.userInfo);
export const useUserToken = () => useUserStore((state) => state.userToken);
export const useUserPermission = () => useUserStore((state) => state.userInfo.permissions);
export const useUserActions = () => useUserStore((state) => state.actions);

export const useSignIn = () => {
  const navigatge = useNavigate();
  const { message } = App.useApp();
  const { setUserToken, setUserInfo } = useUserActions();

  const signInMutation = useMutation({
    mutationFn: userService.signin,
  });

  const signIn = async (data) => {
    try {
      // const res = await signInMutation.mutateAsync(data);
      // const { user, accessToken, refreshToken } = res;
      // setUserToken({ accessToken, refreshToken });
      // setUserInfo(user);
      navigatge(HOMEPAGE, { replace: true });
    } catch (err) {
      message.warning({
        content: err.message,
        duration: 3,
      });
    }
  };

  return signIn;
};


export const useToLogin = () => {
  const { constantObjSSO } = useUserStore();

  const toLogin = () => {
    // window.location.href = `http://${constantObjSSO.SSO_HOST}/esc-sso/logout`
    let url = `http://${constantObjSSO.SSO_HOST
      }/esc-sso/oauth2.0/authorize?client_id=ssoclient&response_type=code&redirect_uri=${location.origin
      }/integration/callback&oauth_timestamp=${new Date().getTime()}&state=${location.origin}/integration/index`
    getLocation().href = url

  };
  return toLogin;
};


export default useUserStore;
